package com.example.casper.Experiment2024.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import com.example.casper.Experiment2024.R;

import java.util.ArrayList;
import java.util.Random;


public class GameView extends SurfaceView implements SurfaceHolder.Callback {
    private Submarine submarine;
    private ArrayList<Bomb> bombs;
    private Bitmap submarineBitmap;
    private Bitmap bombBitmap;
    private boolean isGameOver = false;
    private int score = 0;
    private int bombSpeed = 10;  // 初始炸弹下落速度
    private int bombCount = 5;   // 初始炸弹数量
    private int dodgedBombs = 0;  // 躲过的炸弹数
    private long startTime = 0;  // 游戏开始时间
    private long totalGameTime = 0; // 游戏总时间（从游戏开始到Game Over的时间）
    private long difficultyStartTime = 0; // 用于每10秒周期更新难度的时间
    private Handler handler;
    private Runnable gameLoop;

    public GameView(Context context, AttributeSet attrs) {
        super(context, attrs);
        getHolder().addCallback(this);

        // 加载图片并缩放
        submarineBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.submarine);
        bombBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.bomb);

        // 根据屏幕大小缩放图片
        submarineBitmap = Bitmap.createScaledBitmap(submarineBitmap, 120, 120, false); // 调整潜艇的尺寸
        bombBitmap = Bitmap.createScaledBitmap(bombBitmap, 60, 60, false); // 调整炸弹的尺寸

        submarine = new Submarine(getWidth() / 2 - submarineBitmap.getWidth() / 2, getHeight() - 150);
        bombs = new ArrayList<>();
        handler = new Handler();
        gameLoop = new Runnable() {
            @Override
            public void run() {
                update();
                draw();
                handler.postDelayed(this, 30); // 每30ms更新一次游戏
            }
        };
        setFocusable(true);
        setFocusableInTouchMode(true);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        // 获取潜艇的宽度和高度
        int submarineWidth = submarineBitmap.getWidth();
        int submarineHeight = submarineBitmap.getHeight();

        // 计算潜艇的初始位置，确保它位于屏幕内
        float startX = (getWidth() - submarineWidth) / 2;  // 居中
        float startY = getHeight() - submarineHeight - 100; // 距离底部 100px

        // 确保潜艇不会超出屏幕
        startX = Math.max(0, Math.min(startX, getWidth() - submarineWidth));
        startY = Math.max(0, Math.min(startY, getHeight() - submarineHeight));

        submarine.setX(startX);
        submarine.setY(startY);

        bombs.clear();  // 清空炸弹

        // 启动游戏循环
        handler.post(gameLoop);
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        // 这个方法可以在屏幕尺寸变化时做处理
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        // 停止游戏循环
        handler.removeCallbacks(gameLoop);
    }

    public void startGame() {
        score = 0;
        isGameOver = false;
        bombSpeed = 10;  // 初始炸弹速度
        bombCount = 5;   // 初始炸弹数量
        dodgedBombs = 0; // 重置躲过的炸弹数
        bombs.clear();   // 清空炸弹

        // 记录游戏开始时的时间
        startTime = System.currentTimeMillis();
        totalGameTime = 0; // 初始化游戏总时间
        difficultyStartTime = System.currentTimeMillis(); // 初始化周期开始时间
    }

    public void stopGame() {
        handler.removeCallbacks(gameLoop);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 根据按键控制潜艇移动
        Log.d("GameView", "Key Pressed: " + keyCode);
        switch (keyCode) {
            case KeyEvent.KEYCODE_W:  // W 键
                if (submarine.getY() > 0) {
                    submarine.setY(submarine.getY() - 10); // 向上移动
                }
                break;
            case KeyEvent.KEYCODE_A:  // A 键
                if (submarine.getX() > 0) {
                    submarine.setX(submarine.getX() - 10); // 向左移动
                }
                break;
            case KeyEvent.KEYCODE_S:  // S 键
                if (submarine.getY() < getHeight() - submarineBitmap.getHeight()) {
                    submarine.setY(submarine.getY() + 10); // 向下移动
                }
                break;
            case KeyEvent.KEYCODE_D:  // D 键
                if (submarine.getX() < getWidth() - submarineBitmap.getWidth()) {
                    submarine.setX(submarine.getX() + 10); // 向右移动
                }
                break;
        }
        return true; // 返回 true 表示事件已经处理
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        // 释放按键时不做处理，默认即可停止潜艇移动
        return false;
    }

    public void update() {
        if (isGameOver) {
            return;  // 游戏结束后不再更新
        }

        // 计算从游戏开始到现在的总时间
        totalGameTime = System.currentTimeMillis() - startTime;

        // 每 10 秒增加炸弹速度和数量
        if (System.currentTimeMillis() - difficultyStartTime > 10000) {
            bombSpeed += 2;  // 增加炸弹下落速度
            bombCount = Math.min(10, bombCount + 1);  // 最多10个炸弹
            difficultyStartTime = System.currentTimeMillis(); // 更新周期时间
        }

        // 更新炸弹位置
        for (Bomb bomb : bombs) {
            bomb.setY(bomb.getY() + bombSpeed); // 炸弹向下移动
            if (bomb.getY() > getHeight()) {
                bomb.setY(0); // 如果炸弹超出屏幕，重新从顶部开始
                bomb.setX(randomPosition()); // 随机 X 坐标
                dodgedBombs++; // 躲过一个炸弹
            }
            // 检查碰撞
            if (checkCollision(submarine, bomb)) {
                isGameOver = true;
            }
        }

        // 增加分数
        if (!isGameOver) {
            score++;
        }

        // 每隔一定时间增加一个新的炸弹
        if (bombs.size() < bombCount && Math.random() < 0.1) {
            bombs.add(new Bomb(randomPosition(), 0));
        }
    }

    public void draw() {
        Canvas canvas = getHolder().lockCanvas();
        if (canvas == null) return;

        canvas.drawColor(Color.BLACK); // 清空屏幕

        Paint paint = new Paint();
        paint.setColor(Color.WHITE);
        paint.setTextSize(50);

        // 绘制分数
        canvas.drawText("Score: " + score, 50, 100, paint);

        // 绘制躲过的炸弹数
        canvas.drawText("Dodged: " + dodgedBombs, 50, 150, paint);

        // 绘制坚持的时间
        canvas.drawText("Time: " + (totalGameTime / 1000) + "s", 50, 200, paint);

        // 绘制潜艇
        canvas.drawBitmap(submarineBitmap, submarine.getX(), submarine.getY(), paint);

        // 绘制炸弹
        for (Bomb bomb : bombs) {
            canvas.drawBitmap(bombBitmap, bomb.getX(), bomb.getY(), paint);
        }

        // 游戏结束时绘制文本
        if (isGameOver) {
            paint.setTextSize(100);
            paint.setColor(Color.RED);
            canvas.drawText("GAME OVER", getWidth() / 2 - 250, getHeight() / 2, paint);
        }

        getHolder().unlockCanvasAndPost(canvas);
    }

    public boolean checkCollision(Submarine submarine, Bomb bomb) {
        Rect submarineRect = new Rect((int) submarine.getX(), (int) submarine.getY(),
                (int) submarine.getX() + submarine.getWidth(), (int) submarine.getY() + submarine.getHeight());
        Rect bombRect = new Rect((int) bomb.getX(), (int) bomb.getY(),
                (int) bomb.getX() + bomb.getWidth(), (int) bomb.getY() + bomb.getHeight());

        return Rect.intersects(submarineRect, bombRect);
    }

    public float randomPosition() {
        Random rand = new Random();
        return rand.nextFloat() * (getWidth() - 100); // 随机 X 坐标
    }
}